import { Controller, Get, Param, Res, Sse } from "@nestjs/common";
import type { Response } from 'express'
import { readFileSync } from "fs";
import { interval, Observable } from "rxjs";
import { Public } from "src/decorators/is-public.decorator";
import { map } from 'rxjs/operators';

@Controller('sse')
export class SseController {
    @Public()
    @Get('')
    index(@Res() response: Response) {
        response.type('text/html')
            .send(readFileSync('./src/sse/index.html', 'utf-8'))
    }

    @Public()
    @Sse('test')
    sse(): Observable<MessageEvent> {
        return interval(1000).pipe(
            map((_) => ({ data: { hello: 'world' } }) as MessageEvent),
        );
    }

    @Public()
    @Sse('task/:taskId')
    sendTaskProgress(@Param('taskId') taskId: string): Observable<MessageEvent> {
        return interval(100).pipe(
            map((count) => {
                console.log(" count:", count)
                const progress = Math.min(count * 1, 100);
                return {
                    type: 'progressUpdate',
                    data: {
                        taskId,
                        progress,
                        message: progress === 100 ? 'Task completed' : `Working in...${progress}%`,
                        status: progress === 100 ? 'COMPLETED' : 'IN_PROGRESS',
                    },
                } as MessageEvent
            })
        );
    }
}